package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.db.mapper.MarketStorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class WxStorageServiceImpl implements WxStorageService {
    @Value("${file.upload-dir}")
    private String path;

    @Value("${file.file-url}")
    private String requestAddr;
    @Value("${file.file-request}")
    private String requestPath;
    @Value("${server.port}")
    private String port;

    @Autowired
    MarketStorageMapper marketStorageMapper;

    @Transactional
    @Override
    public MarketStorage upload(MultipartFile file) throws IOException {
        MarketStorage marketStorage = new MarketStorage();
        File baseDir = new File(path);
        if (!baseDir.exists()) {
            Files.createDirectories(baseDir.toPath());
        }
        // 保存文件
        String originalFilename = file.getOriginalFilename();
        String aName = UUID.randomUUID()+file.getOriginalFilename();
        String fileName=aName.substring(30);
        marketStorage.setKey(fileName);
        marketStorage.setName(originalFilename);
        marketStorage.setType(file.getContentType());
        marketStorage.setSize((int) file.getSize());
        marketStorage.setUrl(requestAddr+":"+port+"/"+requestPath+"/"+fileName);
        marketStorage.setAddTime(LocalDateTime.now());
        marketStorage.setUpdateTime(LocalDateTime.now());
        marketStorage.setDeleted(false);
        int insert = marketStorageMapper.insert(marketStorage);
        file.transferTo(new File(path+"/" + fileName));
        if (insert!=1){
            return null;
        }
        return marketStorage;
    }

    @Override
    public MarketStorage uploadAliyun(MultipartFile file,String key) {
        MarketStorage marketStorage = new MarketStorage();

        marketStorage.setKey(key);
        marketStorage.setName(file.getOriginalFilename());
        marketStorage.setType(file.getContentType());
        marketStorage.setSize((int) file.getSize());
        marketStorage.setUrl(requestAddr+"/"+key);
        marketStorage.setAddTime(LocalDateTime.now());
        marketStorage.setUpdateTime(LocalDateTime.now());
        marketStorage.setDeleted(false);
        int insert = marketStorageMapper.insert(marketStorage);
        if (insert!=1){
            return null;
        }
        return marketStorage;
    }
}
